package com.starsoft.frame.base.dao;

import java.io.InputStream;
import java.sql.Blob;

import org.hibernate.Hibernate;
import org.springframework.stereotype.Repository;

import com.starsoft.frame.base.bean.BaseAttachment;
import com.starsoft.frame.core.orm.BaseDao;
import com.starsoft.frame.util.DateUtil;

@Repository
public class AttachmentDao extends BaseDao<BaseAttachment, Integer>{
	
	public BaseAttachment getFile(Integer id){
		return this.get(BaseAttachment.class, id);
	}
	
	public String getFileName(Integer id ){
		try {
			String hql = "select fileName from BaseFile where id = ?0";
			return (String) this.getValue(hql, id);
		} catch (Exception e) {
			return null;
		}
	}

	public Integer saveAttachment(String fileName, InputStream in) {
		try {
			BaseAttachment file = new BaseAttachment();
			file.setCreateTime(DateUtil.getTimestamp());
			file.setFileName(fileName);

			Blob content = Hibernate.getLobCreator(getSession()).createBlob(in, in.available());
			file.setContent(content);
			this.save(file);
			return file.getId();
		} catch (Exception e) {
			return -1;
		}
	}

}
